package com.zzzzzz.sys.platform.menu;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.sys.menu.ZTree;

@Service
public class PlatformMenuService {
	@Resource
	public PlatformMenuDao platformMenuDao;
	
	@Transactional
	public int save(Long platformId, List<Long> menuIds){
		platformMenuDao.delByPlatformId(platformId);
		if(menuIds != null){
			for(Long menuId : menuIds){
				platformMenuDao.add(new PlatformMenu(platformId, menuId));
			}	
		}
		return 1;
	}
	
	public List<ZTree> findListByIdForEdit(Long platformId, Long id) {
		List<ZTree> zTreeList=new ArrayList<ZTree>();
		List<ZTree> list;
		if(id == null){
			list = platformMenuDao.findListByNullPidForEdit(platformId);
		}else{
			list = platformMenuDao.findListByPidForEdit(platformId, id);
		}
		
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		for(ZTree zTree:list){
			zTreeList.add(addLeafMenuForEdit(platformId, zTree));
		}
		return zTreeList;
	}
	
	private ZTree addLeafMenuForEdit(Long platformId, ZTree zTree){
		if(zTree==null){
			return null;
		}
		Long id=zTree.getId();
		if(id == null){
			return null;
		}
		
		List<ZTree> list = findListByIdForEdit(platformId, id);
		if(CollectionUtils.isEmpty(list)){
			zTree.setParent(true);
			return zTree;
		}
		zTree.setChildren(list);
		return zTree;
	}
	
	public List<ZTree> findListByIdForSidebar(Long platformId, Long id) {
		List<ZTree> zTreeList=new ArrayList<ZTree>();
		List<ZTree> list;
		if(id == null){
			list = platformMenuDao.findListByNullPidForSidebar(platformId);
		}else{
			list = platformMenuDao.findListByPidForSidebar(platformId, id);
		}
		
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		for(ZTree zTree:list){
			if(StringUtils.isBlank(zTree.getUrl())){
				zTree.setUrl("javascript:void(0);");
			}
			zTreeList.add(addLeafMenuForSidebar(platformId, zTree));
		}
		return zTreeList;
	}
	
	private ZTree addLeafMenuForSidebar(Long platformId, ZTree zTree){
		if(zTree==null){
			return null;
		}
		Long id=zTree.getId();
		if(id == null){
			return null;
		}
		
		List<ZTree> list = findListByIdForSidebar(platformId, id);
		if(CollectionUtils.isEmpty(list)){
			zTree.setParent(true);
			return zTree;
		}
		for(ZTree zTreeTmp : list){
			if(StringUtils.isBlank(zTreeTmp.getUrl())){
				zTreeTmp.setUrl("javascript:void(0);");
			}
		}
		
		zTree.setChildren(list);
		return zTree;
	}
}
